package com.ktjy.t382.ch01.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ktjy.t382.ch01.entity.vo.R;
import jakarta.annotation.Resource;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;

import java.io.IOException;

//将自定义的过滤器注册
//@WebFilter(urlPatterns = "/user/*", filterName = "myFilter")
public class MyFilter implements Filter {

    @Resource
    ObjectMapper objectMapper;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //Filter.super.init(filterConfig);
        System.out.println("MyFilter....init");
    }

    //localhost:81/ch01/user/get  发送一个http请求   请求体 请求头
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletResponse.setContentType("text/plain;charset=UTF-8");
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;

        String authorization = httpServletRequest.getHeader("Authorization");
        if (authorization != null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            //重定向、转发、或者返回json数据给前端
            servletResponse.getWriter().println(objectMapper.writeValueAsString(R.fail("token is null")));
        }
    }

    @Override
    public void destroy() {
        //Filter.super.destroy();
        System.out.println("MyFilter....destroy");
    }
}
